package cn.hs.lyxf.exception;

import cn.hs.lyxf.result.JsonResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Package: cn.mzy.xfcc.exception
 * @ClassName: GlobalExceptionHandler
 * @Date:2022/11/17 9:56
 * @Description: 全局统一异常处理
 */
// 会封装为JSON
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return JsonResult.error(GlobalErrorCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomizeException.class)
    public JsonResult globalExceptionHandler(GlobalCustomizeException e) {
        e.printStackTrace();
        return JsonResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // debug打印出来看 得到数组
        e.printStackTrace();
        // 得到所有异常提示信息
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        // new一个stringbuilder保存数据
        StringBuilder builder = new StringBuilder();
        // 遍历所有异常提示信息，保存到builder数组
        errors.forEach(objectError -> builder.append(objectError.getDefaultMessage()).append(";"));
        return JsonResult.error(builder.toString());
    }
}